import rsa
import base64
import hashlib
from jose import jwt


class Hash:
    """hash 计算"""
    def __init__(self, salt='my2024', algorithm='sha256'):
        self.salt = salt
        self.algorithm = algorithm

    def init(self, salt: str = None, algorithm: str = None):
        self.salt = salt
        self.algorithm = algorithm

    def calculate(self, value):
        """hash计算"""
        func = getattr(hashlib, self.algorithm)
        m = func(self.salt.encode()) if self.salt else func()
        m.update(value.encode())
        return m.hexdigest()


class RSA:
    """Rsa封装使用"""
    def __init__(self, private_key=None, public_key=None):
        self.private_key = None
        self.public_key = None

        if private_key and public_key:
            self.init(private_key, public_key)

    def init(self, private_key=None, public_key=None):
        self.private_key = rsa.PrivateKey.load_pkcs1(base64.b64decode(private_key.encode()))
        self.public_key = rsa.PublicKey.load_pkcs1(base64.b64decode(public_key.encode()))

    def encrypt(self, value: str) -> str:
        """rsa加密 b64编码"""
        return base64.b64encode(rsa.encrypt(value.encode(), self.public_key)).decode()

    def decrypt(self, value) -> str:
        """b64解码 rsa解密"""
        return rsa.decrypt(base64.b64decode(value.encode()), self.private_key).decode()


class JWT:
    """"""
    def __init__(self, secret_key='secret_key', algorithm='HS256'):
        self.secret_key = secret_key
        self.algorithm = algorithm

    def init(self, secret_key=None, algorithm=None):
        self.secret_key = secret_key
        self.algorithm = algorithm

    def encode(self, value, **kwargs):
        """编码 生成token"""
        encoded_jwt = jwt.encode(value, self.secret_key, algorithm=self.algorithm, **kwargs)
        return encoded_jwt

    def decode(self, token, **kwargs):
        """解码token"""
        return jwt.decode(token, self.secret_key, algorithms=[self.algorithm], **kwargs)


class Permission:

    APIKeyPrefix = 'permission:apikey'
    TokenPrefix = 'permission:token'
    KeyPrefix = 'permission:key'

    def __init__(self, enabled=False, redis=None, oauth2_scheme=None):
        self.enabled = enabled
        self.redis = redis
        self.oauth2_scheme = oauth2_scheme

    def init(self, enabled=False, redis=None, oauth2_scheme=None):
        self.enabled = enabled
        self.redis = redis
        self.oauth2_scheme = oauth2_scheme

    def check_apikey(self, apikey):
        return self.redis.redis.get(f'{self.APIKeyPrefix}:{apikey}')

    def check_token(self, token):
        return self.redis.redis.get(f'{self.TokenPrefix}:{token}')

    def get_user(self, key):
        return self.redis.redis.get(f'{self.KeyPrefix}:{key}')


security_hash = Hash()
security_jwt = JWT()
security_rsa = RSA()
permission = Permission()


if __name__ == '__main__':
    security_hash.init(salt='my2024', algorithm='sha256')
    security_jwt.init(secret_key='secret_key', algorithm='HS256')
    security_rsa.init(private_key='LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlDWUFJQkFBS0JnUUNPcm5BMDRjeTNSVGZvOW1NaGhVK04yeEtaUG5ERjZwSkVRbjNjSTF5aHdSVGx5aVBPCkphNlVVNTBuaURmNmZsamdnYmluNGYyZUs1WkRWbXpkN3J0M3ExcEowWjl3N2tSd1ZSYTM5ZlRqY0tqdlo3UDQKc2xaM1F3dVZoRk5VSGpjZ2RCUzN0aEUzVldZbTNUYkNHOVdEV2dqMUpEd3ExWi92d2cyR3ZKenpQUUlEQVFBQgpBb0dBRXROVFBMYjZNc2d3TzAyZkFNSTlIK05pemROZVA4N1dZNmsrUC9odWRXMHJXN0pURFJVTnRzWmRldVRQCk5mN0xyVHVRYUo0NXYwL1M4S21MZVJNRnJsUzQ3S2ZLOFFHOFM4Rzk3SEZGazdjKzZRdlNEUDJ3dGM5Y2J0OVEKdHg2TVJJQ0tMZnMvV25UbS9xaUZhNWRsTnBWVlB4NmtrUWhBSndjWnFTNTh3TUVDUlFDY1FLaUorN2wxbEs1dApweFRFNkZ1STVHc0VIVC9RL3NpMm0zbDhOMWdINEZmb2YvcG5UQVpqMldxK3cvcyt2MVFVLzlkQXRZazNSaFN5CmNXSXRabkhlRXR4bGNRSTlBT25EN25xT3JURXZ2bUF3SC9lU2o0MHRVRllyM1FHT3A1T2NNWFJoWWFYN1c2WUoKSC9TV0FVaTVPVGhDSnhneWhHM0RnYW51RS9FbXp2QlVqUUpFUjlCcjVlYzlDTzZKOExuUEVPVWVWTjl1MUJoQgpZV1FJaWUwUk8rY1AzYWJkb0cxWmdDcHY4V3BXNWxDYTQrNzV6U0Q5SksrSzNrMm1hNUV6SjF5alR3YnFKdkVDClBCUTdTT0NDaUtyQkh4RGtHV0FyNXhDbzQxTVI2TWJCdWU4a2pZTXRDbTU3R3F0OERxLzBhNWdIcjlRV3BadUsKZzd1Y09CU2s3a1RvdnZBOTRRSkZBSk1kUDdpZ09rUFJYeUkyR1hrNWRJSnh2aHZTalJrcS9makxMMzRTNGx5agpaaU1leUYzYTRSOFRZQnE1aGpWMWZPUzJIZmJzVXgvdkttaVZuWU42REhabEFaamQKLS0tLS1FTkQgUlNBIFBSSVZBVEUgS0VZLS0tLS0K',
                       public_key='LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tCk1JR0pBb0dCQUk2dWNEVGh6TGRGTitqMll5R0ZUNDNiRXBrK2NNWHFra1JDZmR3alhLSEJGT1hLSTg0bHJwUlQKblNlSU4vcCtXT0NCdUtmaC9aNHJsa05XYk4zdXUzZXJXa25SbjNEdVJIQlZGcmYxOU9Od3FPOW5zL2l5Vm5kRApDNVdFVTFRZU55QjBGTGUyRVRkVlppYmROc0liMVlOYUNQVWtQQ3JWbisvQ0RZYThuUE05QWdNQkFBRT0KLS0tLS1FTkQgUlNBIFBVQkxJQyBLRVktLS0tLQo=')

    t = security_jwt.encode({'user': 'aaa'})
    print(t)
    u = security_jwt.decode(t)
    print(u)
    pwd = security_rsa.encrypt('admin')
    print(pwd)
    pwd = security_rsa.decrypt(pwd)
    print(pwd)
    md5sum = security_hash.calculate('admin')
    print(md5sum)
